const gulp = require('gulp'),
  { gutil, del, filter, compile, ftp, sass, tinify, rollup, watch, browserSync } = require('../../gulp-project'),
  reload = browserSync.reload

function build(globs, done) {
  return gulp.src(globs)
    .pipe(rollup())
    .pipe(gulp.dest('js'))
    .on('finish', done)
}

// scss编译后的css将注入到浏览器里实现更新
gulp.task('sass', function(done) {
  return gulp.src('./scss/*.scss')
    .pipe(sass())
    .pipe(gulp.dest('css'))
    .pipe(reload({ stream: true }))
    .on('finish', done)
})

gulp.task('build-watch', function(done) {
  return gulp.src('src/page-js/*.js')
    .pipe(rollup())
    .pipe(gulp.dest('js'))
    .pipe(reload({ stream: true }))
    .on('finish', done)
})
gulp.task('build', gulp.series('build-watch', 'sass'))

gulp.task('init.js', function(done) {
  return gulp.src(['node_modules/vue/dist/vue.js', 'node_modules/vue/dist/vue.min.js', 'node_modules/babel-polyfill/dist/polyfill.min.js', 'node_modules/vue-resource/dist/vue-resource.min.js', 'node_modules/vconsole/dist/vconsole.min.js'])
    .pipe(gulp.dest('js'))
    .on('finish', done)
})
gulp.task('init.css', function(done) {
  return gulp.src([])
    .pipe(gulp.dest('css'))
    .on('finish', done)
})
gulp.task('clean', function(done) {
  del.sync(['js', 'css', 'temp'])
  done()
})

gulp.task('js-watch', gulp.parallel('build-watch'))

// 静态服务器 + 监听 scss/html 文件
gulp.task('serve', function() {

  browserSync.init({
    server: './',
    port: 1990
  })

  watch('pages/*.html').on('change', reload)
  watch('css/*.css').on('change', reload)
  watch('src/page-js/*.js', gulp.parallel('js-watch', reload))
  watch('scss/*.scss', gulp.parallel('sass', reload))
  watch('src/dev/vue/**/*.js', gulp.parallel('js-watch', reload))
  watch('src/dev/*.js', gulp.parallel('js-watch', reload))
  watch('src/dev/vue/*.vue', gulp.parallel('js-watch', reload))

})

//开发
gulp.task('dev', gulp.series('clean', 'init.js', 'build', 'serve'))

// 代码打包
gulp.task('release', function(done) {

  gulp.src('**')
    .pipe(filter(['src/**']))
    .pipe(compile({
      push: 1,
      env: 3,
      release: 3,
      uri: {
        '{css,images,js}/**': `/fengqiu/$0`
      }
    }, null, false))
    .pipe(gulp.dest('build'))
    .on('finish', done)
})
